//
//  MNDInviteAlertViewController.m
//  minidai
//
//  Created by Vitas on 2018/9/1.
//  Copyright © 2018年 迷你贷. All rights reserved.
//

#import "MNDInviteAlertViewController.h"
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKUI/ShareSDKUI.h>
#import "WeiboSDK.h"
#import "MNDShareModel.h"
#import "MNDLoginUserModel.h"
#import "MNDScanInviteViewController.h"
#import <SDWebImage/UIImageView+WebCache.h>

@interface MNDInviteAlertViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *shareImgView;
@property (weak, nonatomic) IBOutlet UIImageView *scanImgView;
@property (weak, nonatomic) IBOutlet UILabel *recommendCodeLabel;

@end

@implementation MNDInviteAlertViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.alertView.transform = CGAffineTransformMakeScale(0.2, 0.2);
    if (self.inviteModel) {
        self.recommendCodeLabel.text = [NSString stringWithFormat:@"您的专属推荐码：%@",self.inviteModel.invite_code];
//        [self.scanImgView sd_setImageWithURL:[NSURL URLWithString:self.inviteModel.qrcode_img]];
    }
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(dismissAction:)];
    [self.view addGestureRecognizer:tapGesture];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationAction:) name:@"scanImgSaveSuccessNotification" object:nil];
    // Do any additional setup after loading the view.
}

- (void)notificationAction:(NSNotification *)notification {
    [self dismissAlertView];
}

- (void)dismissAction:(UITapGestureRecognizer *)gesture {
    [self dismissAlertView];
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
 
    [UIView animateWithDuration:0.7
                          delay:0.0
         usingSpringWithDamping:0.5
          initialSpringVelocity:0.1
                        options:UIViewAnimationOptionCurveEaseIn
                     animations:^{
                         
                         self.alertView.transform = CGAffineTransformScale(CGAffineTransformIdentity, 1.0, 1.0);
                     }
                     completion:^(BOOL finished) {
                         
                     }];
    
}

//一键分享
- (IBAction)shareAction:(UIButton *)sender {
    [self socialShareAction];
}

//扫码推荐
- (IBAction)scanAction:(UIButton *)sender {
    MNDScanInviteViewController *alertVC = [UIStoryboard viewControllerWithIdentifier:@"MNDScanInviteViewController"];
    alertVC.scanUrl = self.inviteModel.qrcode_img;
    [KeyWindow addSubview:alertVC.view];
    [self addChildViewController:alertVC];
}

- (void)socialShareAction {
    
    WeakSelf(self);
    [NetworkProgressHUD showHud];
    [APIManager sendRequestWithPath:API_USER_SHARE parameters:[MNDSign signedParam] method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        
        if (responseModel.status == ResponseSuccess) {
            [NetworkProgressHUD hideHud];
            NSLog(@"%@", responseModel.data);
            MNDShareModel *shareContent = [MNDShareModel mj_objectWithKeyValues:responseModel.data];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakself shareWithContents:shareContent];
            });
        } else {
            
            NSDictionary *dict = responseModel.msg;
            if (dict && dict.count > 0) {
                [NetworkProgressHUD showHudMsg:dict[@"error"]];
            } else {
                [NetworkProgressHUD showHudMsg:@"获取数据失败，请重试"];
            }
        }
    } onFailure:^(NSError *error) {
        
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (void)shareWithContents: (MNDShareModel *)content {
    NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
    
    NSString *encodeUrl = content.share_url;
    //    [content.share_url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
    
    [shareParams SSDKSetupShareParamsByText: content.share_txt
                                     images: content.share_img
                                        url: [NSURL URLWithString:encodeUrl]
                                      title: content.share_title
                                       type: SSDKContentTypeAuto];
    
    [shareParams SSDKSetupWeChatParamsByText: content.share_txt
                                       title: content.share_title
                                         url: [NSURL URLWithString:encodeUrl]
                                  thumbImage: content.share_img
                                       image: content.share_img
                                musicFileURL: nil
                                     extInfo: nil
                                    fileData: nil
                                emoticonData: nil
                                        type: SSDKContentTypeWebPage
                          forPlatformSubType: SSDKPlatformSubTypeWechatSession];
    
    [shareParams SSDKSetupWeChatParamsByText: content.share_txt
                                       title: content.share_title
                                         url: [NSURL URLWithString:encodeUrl]
                                  thumbImage: content.share_img
                                       image: content.share_img
                                musicFileURL: nil
                                     extInfo: nil
                                    fileData: nil
                                emoticonData: nil
                                        type: SSDKContentTypeWebPage
                          forPlatformSubType: SSDKPlatformSubTypeWechatTimeline];
    
    [shareParams SSDKSetupQQParamsByText: content.share_txt
                                   title: content.share_title
                                     url: [NSURL URLWithString:encodeUrl]
                              thumbImage: content.share_img
                                   image: content.share_img
                                    type: SSDKContentTypeWebPage
                      forPlatformSubType: SSDKPlatformTypeQQ];
    
    //微博分享内容
    [shareParams SSDKSetupSinaWeiboShareParamsByText: content.share_txt
                                               title: content.share_title
                                              images: content.share_img
                                               video: nil
                                                 url: [NSURL URLWithString:encodeUrl]
                                            latitude: 0
                                           longitude: 0
                                            objectID: nil
                                      isShareToStory: NO
                                                type: SSDKContentTypeWebPage];
    
    //使用客户端分享
    [shareParams SSDKEnableUseClientShare];
    
    NSMutableArray *items = [NSMutableArray arrayWithArray:@[@(SSDKPlatformSubTypeWechatSession),
                                                             @(SSDKPlatformSubTypeWechatTimeline),
                                                             @(SSDKPlatformSubTypeQQFriend),
                                                             @(SSDKPlatformTypeSinaWeibo)]];
    
    //    __weak typeof(self) weakSelf = self;
    
    //调用分享的方法
    [ShareSDK showShareActionSheet:self.view
                       customItems:items
                       shareParams:shareParams
                sheetConfiguration:nil
                    onStateChanged:^(SSDKResponseState state, SSDKPlatformType platformType, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error, BOOL end) {
                        
                        if (platformType == SSDKPlatformTypeSinaWeibo) {
                            if (![WeiboSDK isWeiboAppInstalled]) {
                                NSString  *message = @"您未安装微博客户端, 无法分享";
                                [NetworkProgressHUD showHudMsg:message];
                                return;
                            }
                        }
                        
                        switch (state) {
                            case SSDKResponseStateBegin:
                            {
                                
                                NSLog(@"分享开始");
                            }
                                break;
                            case SSDKResponseStateSuccess:
                            {
                                NSLog(@"分享成功!");
                                [NetworkProgressHUD showHudMsg:@"分享成功"];
                            }
                                
                                break;
                            case SSDKResponseStateFail:
                            {
                                NSLog(@"分享失败%@",error);
                                NSString *errMsg = error.userInfo[@"error_message"];
                                if (!errMsg || [errMsg containsString:@"null"]) {
                                    break;
                                }
                                NSString *message = [NSString stringWithFormat:@"分享失败:%@", error.userInfo[@"error_message"]];
                                [NetworkProgressHUD showHudMsg: message];
                            }
                                break;
                            case SSDKResponseStateCancel:
                            {
                                // [MBProgressHUD showHUDAddedTo:weakSelf.view animated:YES];
                                //MBProgressHUD *HUD = [MBProgressHUD HUDForView:weakSelf.view];
                                // HUD.labelText = @"已取消分享";
                                //HUD.mode = MBProgressHUDModeText;
                                //[HUD hide:YES afterDelay:1.5];
                                NSLog(@"分享已取消");
                            }
                                break;
                            default:
                                break;
                        }
                    }];
    //删除和添加平台示例
    //(默认微信，QQ，QQ空间都是直接跳客户端分享，加了这个方法之后，可以跳分享编辑界面分享)
    //        [sheet.directSharePlatforms removeObject:@(SSDKPlatformTypeWechat)];
    //（加了这个方法之后可以不跳分享编辑界面，直接点击分享菜单里的选项，直接分享）
    //    [sheet.directSharePlatforms addObject:@(SSDKPlatformTypeSinaWeibo)];
}

- (void)dismissAlertView {
    [self.view removeFromSuperview];
    [self removeFromParentViewController];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
